package com.tinify.loader;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Properties;

public class ApplicationThread {

    private static final String TINIFY_LIB_PATH = "TINIFY_LIB_PATH";
    private static final String TINIFY_KEYS = "TINIFY_KEYS";
    private static final String TINIFY_COMPRESS_RATIO = "TINIFY_COMPRESS_RATIO";
    private static final String TINIFY_PROPERTIES = "config.properties";

    public static void runMain(String[] args) {

        int argLen = args.length;
        if (argLen == 0) throw new IllegalArgumentException("Please Input Manifest files");
        String fileManifest = args[0];

        String dirName = getBaseDirName(new File(fileManifest));


        ReadProperties readProperties = new ReadProperties(dirName + File.separator + "tinify" + File.separator + TINIFY_PROPERTIES);
        Properties properties = readProperties.readProperties();

        String homePath = null;
        String tinifyKeys = null;
        String tinifyRatio = null;

        if (properties != null) {
            homePath = properties.getProperty(TINIFY_LIB_PATH);
            tinifyKeys = properties.getProperty(TINIFY_KEYS);
            tinifyRatio = properties.getProperty(TINIFY_COMPRESS_RATIO);
        }

        RuntimeClassLoader classLoader = new RuntimeClassLoader();

        if (homePath != null && homePath.length() > 0) {

            File file = new File(homePath);
            if (!file.exists()) {
                file = new File(dirName, homePath);
                homePath = file.getAbsolutePath();
            }
            startInitHomePath(classLoader, homePath);
        }
        if (tinifyKeys == null || tinifyKeys.length() == 0) {
            throw new IllegalArgumentException("Tinify Keys is not found");
        }


        System.out.println("压缩最低限制："+tinifyRatio);

        setTinifyKeys(tinifyKeys);
        setTinifyRatio(tinifyRatio);

        classLoader.startLoadClasses();
        startTinify(fileManifest);

    }

    private static void setTinifyRatio(String tinifyRatio) {

        try {
            if (tinifyRatio == null || tinifyRatio.length() == 0) {
                return;
            }
            float r = Float.parseFloat(tinifyRatio);
            float result = 0.1f;
            if (r < 99.05f && r >= 0.05f) {
                result = r;
            }
            TinifyApplication.get().setRatio(result);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static void setTinifyKeys(String tinifyKeys) {

        String[] keys = tinifyKeys.split(";");
        TinifyApplication.get().setTinifyKeys(keys);
    }

    private static void startTinify(String fileManifest) {

        File manifest = new File(fileManifest);
        if (!manifest.exists()) {
            System.err.println("清单文件不存在！");
            return;
        }
        if (!manifest.isFile()) {
            System.err.println("清单文件类型错误");
            return;
        }

        String dirName = getBaseDirName(manifest);
        System.out.println("dirName : " + dirName);
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(manifest, "r");
            String strline;
            while (((strline = raf.readLine()) != null)) {
                if (strline != null && strline.length() == 0) continue;
                addToCompressFile(dirName, strline);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private static String getBaseDirName(File manifestFile) {

        if (manifestFile == null) return null;

        File adsFile = manifestFile.getAbsoluteFile();
        File parent = adsFile.getParentFile();
        String rootPath = null;
        if (parent != null) {
            rootPath = parent.getAbsolutePath();
        }
        if (rootPath.endsWith(File.separator + ".")) {
            rootPath = rootPath.substring(0, rootPath.length() - 2);
        } else if (rootPath.endsWith(File.separator + "..")) {
            rootPath = rootPath.substring(0, rootPath.length() - 3);
            int lastIndex = rootPath.lastIndexOf(File.separator);
            if (lastIndex >= 0) {
                rootPath = rootPath.substring(0, lastIndex);
            }
        }

        return rootPath;

    }

    private static void addToCompressFile(String dirName, String strline) {
        if (strline == null || strline.length() == 0) return;
        String[] filePaths = strline.split("[;:]+");
        if (filePaths == null || filePaths.length == 0) return;

        File adsFile = null;
        for (String path : filePaths) {
            if(path.startsWith(dirName)){
                adsFile = new File(path);
            }else {
                adsFile = new File(dirName, path);
            }
            String absolutePath = adsFile.getAbsolutePath();
            if (!adsFile.exists()) {
                continue;
            }
            if (!adsFile.isFile()){
                continue;
            }

            if (absolutePath.endsWith(".9.png")) continue;

            System.out.println("file : " + absolutePath);

            if (absolutePath.endsWith(".png") || absolutePath.endsWith(".jpg") || absolutePath.endsWith(".jpeg")) {
                TinifyApplication.get().addFile(adsFile);
            }
        }
    }

    private static void startInitHomePath(RuntimeClassLoader classLoader, String homePath) {
        String[] classesPaths = homePath.split(File.pathSeparator);
        if (classesPaths == null) return;

        for (String path : classesPaths) {
            classLoader.addClassPath(path);
        }
    }


}
